package com.ikun.admin.modules.scheduled.quartz;

import com.ikun.admin.modules.scheduled.entity.Task;
import org.quartz.*;

/**
 * @ClassName ScheduledUtil
 * @Description:
 * @CreateDate: 2024/8/11 22:56
 */
public class ScheduledUtil {

    /**
     * 获取触发器key
     */
    public static TriggerKey getTriggerKey(Long jobId) {
        return TriggerKey.triggerKey(Constant.JOB_NAME + jobId);
    }

    /**
     * 获取jobKey
     */
    public static JobKey getJobKey(Long jobId) {
        return JobKey.jobKey(Constant.JOB_NAME + jobId);
    }

    /**
     * 获取表达式触发器
     */
    public static org.quartz.CronTrigger getCronTrigger(org.quartz.Scheduler scheduler, Long jobId) {
        try {
            return (org.quartz.CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建定时任务
     */
    public static void createScheduleJob(Scheduler scheduler, Task task) {
        try {
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(MyScheduleJob.class).withIdentity(getJobKey(task.getId())).build();

            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCron())
                    .withMisfireHandlingInstructionDoNothing();

            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(task.getId())).withSchedule(scheduleBuilder).build();

            //放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(Constant.JOB_KEY, task);

            scheduler.scheduleJob(jobDetail, trigger);

            //暂停任务
            if (task.getSataus() == Constant.JOB_STATUS_SUCCESS) {
                pauseJob(scheduler, task.getId());
            }
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 暂停任务
     */
    public static void pauseJob(Scheduler scheduler, Long jobId) {
        try {
            scheduler.pauseJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 恢复任务
     */
    public static void resumeJob(Scheduler scheduler, Long jobId) {
        try {
            scheduler.resumeJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 删除定时任务
     */
    public static void deleteScheduleJob(Scheduler scheduler, Long jobId) {
        try {
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
